<template>
  <el-card class="box-card">
    <template #header>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <el-button type="primary" @click="navigateToAddUser">
          添加用户
        </el-button>
        <el-input
            v-model="searchQuery"
            placeholder="搜索用户..."
            prefix-icon="el-icon-search"
            clearable
            style="width: 300px"
        ></el-input>
      </div>
    </template>

    <!-- 表格 -->
    <el-table
        :data="paginatedUsers"
        border
        style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="账号" width="120"></el-table-column>
      <el-table-column prop="password" label="密码" width="120"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '封禁' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="role" label="角色" width="100"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="warning" size="mini" @click="navigateToUpdateUser(scope.row.id)">编辑</el-button>
          <el-button type="danger" size="mini" @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="filteredUsers.length"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px"
    ></el-pagination>
  </el-card>
</template>

<script>
import { ulist, dd } from "@/api/auth";

export default {
  name: "UserManagement",
  data() {
    return {
      users: [],
      currentPage: 1,
      pageSize: 10,
      searchQuery: "",
    };
  },
  computed: {
    filteredUsers() {
      if (!this.searchQuery) return this.users;
      const query = this.searchQuery.toLowerCase();
      return this.users.filter(
          (user) =>
              user.username.toLowerCase().includes(query) ||
              user.nickname.toLowerCase().includes(query) ||
              user.email.toLowerCase().includes(query)
      );
    },
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.filteredUsers.slice(start, start + this.pageSize);
    },
  },
  methods: {
    fetchUsers() {
      ulist()
          .then((res) => {
            if (res.code === 200) {
              this.users = res.data;
            } else {
              this.$message.error("获取用户列表失败：" + res.msg);
            }
          })
          .catch((error) => {
            console.error(error);
            this.$message.error("获取用户列表失败：网络异常");
          });
    },
    navigateToAddUser() {
      this.$router.push("/add");
    },
    navigateToUpdateUser(userId) {
      this.$router.push(`/update?id=${userId}`);
    },
    confirmDelete(userId) {
      this.$confirm("确定删除该用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.deleteUser(userId);
          })
          .catch(() => {
            this.$message.info("已取消操作");
          });
    },
    deleteUser(userId) {
      dd(userId)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.fetchUsers();
            } else {
              this.$message.error("删除失败：" + res.msg);
            }
          })
          .catch((error) => {
            console.error(error);
            this.$message.error("网络异常，删除失败");
          });
    },
    handleSizeChange(size) {
      this.pageSize = size;
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
  },
  mounted() {
    this.fetchUsers();
  },
};
</script>

<style scoped>
.user-management {
  padding: 30px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.box-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.add-user-button {
  float: right;
  margin-top: -5px;
}

el-input {
  width: 300px;
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
  border-radius: 6px;
}

.el-table .el-button {
  margin: 4px 0;
}

.el-pagination {
  margin-top: 30px;
  text-align: center;
}

</style>
